package xyz.syyrjx.blog.util.site;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import xyz.syyrjx.blog.entity.BaiduSiteResponse;
import xyz.syyrjx.blog.entity.site.UrlSend;
import xyz.syyrjx.blog.util.ConstValuePool;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/2/20 15:43
 * @description ...
 * @since v0.0.1
 */
@Component
public class BaiduSubmitUtil implements SiteSubmitUtil {

    private static final Logger logger = LoggerFactory.getLogger(BaiduSubmitUtil.class);

    public static  String endpoint;

    private static RestTemplate restTemplate;

    static {
        // restTemplate初始化、拦截器设置
        BaiduSubmitUtil.restTemplate = new RestTemplate();
        BaiduSubmitUtil.restTemplate.getInterceptors().add((request, body, execution) -> {
            HttpHeaders headers = request.getHeaders();
            headers.add("User-Agent", "curl/7.12.1");
            headers.add("Host", "data.zz.baidu.com");
            headers.add("Content-Type", "text/plain");
            return execution.execute(request,body);
        });
    }

    @Override
    public List<String> submit(List<UrlSend> urlSendList) throws DocumentException, JsonProcessingException {
        List<String> allAllowUrl = SiteMapUtil.getAllAllowUrl();
        StringBuilder requestBuilder = new StringBuilder();
        // 筛去已经发送了的url
        List<String> urlNeedSend = allAllowUrl.stream().filter(url -> {
            for (UrlSend urlSend : urlSendList) {
                if (urlSend.getUrl().equals(url)) {
                    return false;
                }
            }
            return true;
        }).limit(5).collect(Collectors.toList());
        if (urlNeedSend.size() == 0) {
            logger.info("没有需要同步的url");
            return ConstValuePool.EMPTY_STRING_LIST;
        }
        // 拼接请求体
        for (String url : urlNeedSend) {
            requestBuilder.append(url).append("\r\n");
        }
        int length = requestBuilder.length();

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(endpoint, requestBuilder.toString(), String.class);
        logger.info("返回原始信息为：{}", stringResponseEntity);
        BaiduSiteResponse baiduSiteResponse =
                ConstValuePool.OBJECT_MAPPER
                        .readValue(stringResponseEntity.getBody(),BaiduSiteResponse.class);
        if (baiduSiteResponse == null) {
            return ConstValuePool.EMPTY_STRING_LIST;
        }
        if (baiduSiteResponse.getNot_same_site() == null) {
            baiduSiteResponse.setNot_same_site(ConstValuePool.EMPTY_STRING_LIST);
        }
        if (baiduSiteResponse.getNot_valid() == null) {
            baiduSiteResponse.setNot_valid(ConstValuePool.EMPTY_STRING_LIST);
        }
        logger.info("失败的url:\r\nnot_same_site:{}\r\nnot_valid:{}",
                baiduSiteResponse.getNot_same_site().toString(),
                baiduSiteResponse.getNot_valid().toString());

        return urlNeedSend.stream()
                // 过滤失败的url
                .filter(data -> !baiduSiteResponse.getNot_same_site().contains(data))
                .filter(data -> !baiduSiteResponse.getNot_valid().contains(data))
                .collect(Collectors.toList());
    }

}
